import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

import '../entity/setting_entity.dart';
import '../event/inventory_event.dart';
import '../main.dart';
import '../serial/send_helper.dart';
import '../util/toast_util.dart';


class SettingCommon extends StatefulWidget {
  const SettingCommon({Key? key}) : super(key: key);

  @override
  State<SettingCommon> createState() => _SettingCommonState();
}

class _SettingCommonState extends State<SettingCommon>  {

  StreamSubscription? actionSubscription;
  SettingEntity? entity;
  final box = GetStorage();

  var _psw = "000000";
  var _apiAddr = "http://8.130.24.109:60060";
  var _faceApiAddr = "http://192.168.2.100:10040";
  var _picApiAddr = "http://8.130.24.109:60040";
  var _appKey = "rSZBWLfFlfjvYKunuqwSRvnY0ZlgUmfL0iZdjs4dpxf2fvZivQxQ4CP3f6OZIHsg";
  var _blockStart = 0;
  var _blockCount = 3;
  var _commonUid = "888888";
  int _slowCountdown = 300;
  int _normalCountdown = 120;
  int _fastCountdown = 20;
  int _scanTime = 4;
  var _auth = "1";
  // var _deviceName = "轩毅";
  // var _publishName = "轩毅";
  var _deviceNo = "rfid_cabinet_001";
  var _hfPort = "/dev/ttyS3";
  var _idPort = "/dev/ttyS0";

  @override
  initState() {
    super.initState();
    // box.remove("setting_entity");
    if(box.hasData('setting_entity')){
      entity = SettingEntity.fromJson(box.read("setting_entity"));

      if(entity!.apiAddr != null){
        _apiAddr = entity!.apiAddr!;
      }
      if(entity!.faceApiAddr != null){
        _faceApiAddr = entity!.faceApiAddr!;
      }
      if(entity!.picApiAddr != null){
        _picApiAddr = entity!.picApiAddr!;
      }
      if(entity!.appKey != null){
        _appKey = entity!.appKey!;
      }
      if(entity!.idPort != null){
        _idPort = entity!.idPort!;
      }
      if(entity!.slowCountdown != null){
        _slowCountdown = entity!.slowCountdown!;
      }
      if(entity!.normalCountdown != null){
        _normalCountdown = entity!.normalCountdown!;
      }
      if(entity!.fastCountdown != null){
        _fastCountdown = entity!.fastCountdown!;
      }
      if(entity!.auth != null){
        _auth = entity!.auth!;
      }
      if(entity!.deviceNo != null){
        _deviceNo = entity!.deviceNo!;
      }
      if(entity!.commonUid != null){
        _commonUid = entity!.commonUid!;
      }
      if(entity!.psw != null){
        _psw = entity!.psw!;
      }
      if(entity!.hfPort != null){
        _hfPort = entity!.hfPort!;
      }
      if(entity!.isUltra != null){
        isUltra.value = entity!.isUltra!;
      }

      if(entity!.blockCount != null){
        _blockCount = entity!.blockCount!;
      }
      if(entity!.blockStart != null){
        _blockStart = entity!.blockStart!;
      }
      if(entity!.scanTime != null){
        _scanTime = entity!.scanTime!;
      }
    }else{
      entity = SettingEntity();
    }
    actionSubscription = eventFactory.on<InventoryEvent>().listen((event) {
        BotToast.closeAllLoading();
        Get.defaultDialog(
          title: "",
          titlePadding:EdgeInsets.zero,
          middleText: event.data.isNotEmpty?'盘点成功: ${event.data.length}本':"盘点失败",
          middleTextStyle: TextStyle(
            color: const Color(0xFF000000),
            fontSize: 8.sp,
          ),
          radius: 4.sp,
        );
    });
  }


  @override
  void dispose() {
    super.dispose();
    actionSubscription?.cancel();
    actionSubscription = null;
  }

  _apiWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  api地址 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 200.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _apiAddr = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _apiAddr,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _apiAddr.length))
            )),
          ),
        ),
      ],
    );
  }


  _faceWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  人脸api地址 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 200.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _faceApiAddr = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _faceApiAddr,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _faceApiAddr.length))
            )),
          ),
        ),
      ],
    );
  }


  _picApiWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  图片api地址 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 200.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _picApiAddr = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _picApiAddr,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _picApiAddr.length))
            )),
          ),
        ),
      ],
    );
  }

  _appKeyWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  appKey ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 250.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _appKey = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _appKey,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _appKey.length))
            )),
          ),
        ),
      ],
    );
  }

  RxBool isUltra = RxBool(false);


  _readerWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  读写器串口号",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 50.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            keyboardType: TextInputType.number,
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _hfPort = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _hfPort.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _hfPort.toString().length))
            )),
          ),
        ),
        Text("  读卡器串口号",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 50.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            keyboardType: TextInputType.number,
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _idPort = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _idPort.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _idPort.toString().length))
            )),
          ),
        ),
        // Text("  起始块",   style: TextStyle(fontSize: 8.sp),),
        // Container(
        //   width: 20.w,
        //   height: 20.h,
        //   margin: EdgeInsets.all(5.r),
        //   child: TextField(
        //     keyboardType: TextInputType.number,
        //     decoration:  InputDecoration(
        //       border:  const OutlineInputBorder(),
        //       contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
        //     ),
        //     style: TextStyle(fontSize: 8.sp),
        //     onChanged: (value){
        //       _blockStart = int.tryParse(value)??0;
        //     },
        //     controller: TextEditingController.fromValue(TextEditingValue(
        //         text: _blockStart.toString(),
        //         selection: TextSelection.fromPosition(
        //             TextPosition(
        //                 affinity: TextAffinity.downstream,
        //                 offset: _blockStart.toString().length))
        //     )),
        //   ),
        // ),
        // Text("  块数量",   style: TextStyle(fontSize: 8.sp),),
        // Container(
        //   width: 20.w,
        //   height: 20.h,
        //   margin: EdgeInsets.all(5.r),
        //   child: TextField(
        //     keyboardType: TextInputType.number,
        //     decoration:  InputDecoration(
        //       border:  const OutlineInputBorder(),
        //       contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
        //     ),
        //     style: TextStyle(fontSize: 8.sp),
        //     onChanged: (value){
        //       _blockCount = int.tryParse(value)??0;
        //     },
        //     controller: TextEditingController.fromValue(TextEditingValue(
        //         text: _blockCount.toString(),
        //         selection: TextSelection.fromPosition(
        //             TextPosition(
        //                 affinity: TextAffinity.downstream,
        //                 offset: _blockCount.toString().length))
        //     )),
        //   ),
        // ),
        Text("盘点次数 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 20.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            keyboardType: TextInputType.number,
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _scanTime = int.tryParse(value)??0;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _scanTime.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _scanTime.toString().length))
            )),
          ),
        ),
        //
        // Text("  高频",   style: TextStyle(fontSize: 8.sp),),
        // Obx(() => Switch(
        //     value: isUltra.value,
        //     onChanged: (value) {
        //       isUltra.value = value;
        //     }
        // ),),
        // Text("超高频    ",   style: TextStyle(fontSize: 8.sp),),
      ],
    );
  }

  _commonUidWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  公用账户Id ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 200.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _commonUid = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _commonUid,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _commonUid.length))
            )),
          ),
        ),
      ],
    );
  }



  _countDownWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  倒计时配置(秒)：",   style: TextStyle(fontSize: 8.sp),),
        Text("  慢速",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 30.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            keyboardType: TextInputType.number,
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              if(int.tryParse(value) != null){
                _slowCountdown = int.tryParse(value)!;
              }

            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _slowCountdown.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _slowCountdown.toString().length))
            )),
          ),
        ),
        Text(" 常规 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 30.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            keyboardType: TextInputType.number,
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              if(int.tryParse(value) != null){
                _normalCountdown = int.tryParse(value)!;
              }
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _normalCountdown.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _normalCountdown.toString().length))
            )),
          ),
        ),
        Text(" 快速 ",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 30.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            keyboardType: TextInputType.number,
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              if(int.tryParse(value) != null){
                _fastCountdown = int.tryParse(value)!;
              }
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _fastCountdown.toString(),
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _fastCountdown.toString().length))
            )),
          ),
        ),
      ],
    );
  }


  _authWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  输入对应数字排序,首位为默认方式",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 50.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _auth = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _auth,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _auth.length))
            )),
          ),
        ),
      ],
    );
  }


  _deviceNoWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  设备号",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 200.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _deviceNo = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _deviceNo,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _deviceNo.length))
            )),
          ),
        ),
        TextButton(onPressed: () {
          _saveDevice();
        }, child: Text('保存配置',   style: TextStyle(fontSize: 8.sp))),
      ],
    );
  }


  _pswWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [
        Text("  管理员密码",   style: TextStyle(fontSize: 8.sp),),
        Container(
          width: 200.w,
          height: 20.h,
          margin: EdgeInsets.all(5.r),
          child: TextField(
            decoration:  InputDecoration(
              border:  const OutlineInputBorder(),
              contentPadding: const EdgeInsets.only(left: 5, right: 5, top: 0, bottom: 0).r,
            ),
            style: TextStyle(fontSize: 8.sp),
            onChanged: (value){
              _psw = value;
            },
            controller: TextEditingController.fromValue(TextEditingValue(
                text: _psw,
                selection: TextSelection.fromPosition(
                    TextPosition(
                        affinity: TextAffinity.downstream,
                        offset: _psw.length))
            )),
          ),
        ),
      ],
    );
  }

  _actionWidget(){
    return Row(
      mainAxisAlignment: MainAxisAlignment.start,
      children: [

        TextButton(onPressed: () {
          BotToast.showLoading();
          hfSerialPortHelper.sendData(inventory());
        }, child: Text('盘点',   style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () {
          hfSerialPortHelper.sendData(openDoor());
        }, child: Text('开门',   style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () {
          hfSerialPortHelper.sendData(openLight());
        }, child: Text('开灯',   style: TextStyle(fontSize: 8.sp))),
        TextButton(onPressed: () {
          hfSerialPortHelper.sendData(closeLight());
        }, child: Text('关灯',   style: TextStyle(fontSize: 8.sp))),
      ],
    );
  }

  _saveDevice(){
    entity!.deviceNo = _deviceNo;
    entity!.apiAddr = _apiAddr;
    entity!.picApiAddr = _picApiAddr;
    entity!.faceApiAddr = _faceApiAddr;
    entity!.appKey = _appKey;
    entity!.slowCountdown = _slowCountdown;
    entity!.normalCountdown = _normalCountdown;
    entity!.fastCountdown = _fastCountdown;
    entity!.auth = _auth;
    entity!.commonUid = _commonUid;
    entity!.isUltra = isUltra.value;
    entity!.psw = _psw;
    entity!.blockStart = _blockStart;
    entity!.blockCount = _blockCount;
    entity!.scanTime = _scanTime;
    entity!.hfPort = _hfPort;
    entity!.idPort = _idPort;
    box.write('setting_entity', entity!.toJson());
    toastWarn('保存成功');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("配置"),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back_ios),
          onPressed: (){

            if(box.hasData('setting_entity')){
              settingEntity = SettingEntity.fromJson(box.read("setting_entity"));
            }
            Get.back();
          },
        ),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _deviceNoWidget(),
          _pswWidget(),
          _apiWidget(),
          _faceWidget(),
          _picApiWidget(),
          _appKeyWidget(),
          _commonUidWidget(),
          _countDownWidget(),
          Text("  默认认证方式(1=读者卡，2=人脸)",   style: TextStyle(fontSize: 8.sp),),
          _authWidget(),
          _readerWidget(),
          _actionWidget()
        ],
      ),
    );
  }
}

